#include"list.h"

head * list_create(int initsize)
{
     head *current = malloc(sizeof(head));
     if (current == NULL)
          return NULL;
     current->size = initsize;    //用户数据类型的大小
     current->first.data = NULL;
     current->first.left = &current->first;
     current->first.right = &current->first;
     return current;
}
int list_insert(head * ptr,const void * data,int choose)
{
     struct node *current = malloc(sizeof(struct node));
     if(current == NULL)
          return -1;
     current->data = malloc(sizeof(ptr->size));
     if(current->data == NULL)
          return -2;
     memcpy(current->data, data, ptr->size);
     if (choose == INSERT_FORWORD)
     {
          current->left = &ptr->first;
          current->right = ptr->first.right;
     }
     else
     {
          current->right = &ptr->first;
          current->left = ptr->first.left;
     }
     current->left->right = current;
     current->right->left = current;
     return 0;
}

int list_insert(head * ptr,const void * data,int choose)
{
     struct node *p = malloc(sizeof(*p));
     if (p == NULL)
          return -1;
     p->data = malloc(sizeof(ptr->size));
     if (p->data == NULL)
          return -2;

     memcpy(p->data, data, ptr->size);
     if (choose == INSERT_FORWORD)
     {
          p->left = &ptr->first;
          p->right = ptr->first.right;
     }
     else if(choose == INSERT_END)
     {
          p->left = ptr->first.left;
          p->right = &ptr->first;

     }
     p->left->right = p;
     p->right->left = p;
     return 0;
}
void list_show(head * ptr,list_op *op)
{
     struct node *current = ptr->first.right;
     while (current != &ptr->first)
     {
          op(current->data);
          current = current->right;
     }
     printf("\n");
}
void list_destory(head ** ptr)
{
     struct node * current = (*ptr)->first.right;
     struct node * pre = NULL;
     while(current != &(*ptr)->first)
     {
          pre = current;
          current = current->right;
          free(pre->data);
          free(pre);
     }
     free(*ptr);
     *ptr = NULL;
}